<template>
	<view class="certified-owners-page">
		<!-- 自定义头部 -->
		<headerSlot :propsColor="'#fff'">
			<template v-slot:header>
				<view class="header-container" @click="closePage()">
					<view class="back-btn">
						<text class="cuIcon-back"></text>
					</view>
					<view class="page-title">
						业主认证
					</view>
				</view>
			</template>
		</headerSlot>

		<!-- 主要内容区域 -->
		<view class="content-container">
			<!-- 表单区域 -->
			<view class="form-section">
				<!-- 基础信息卡片 -->
				<view class="form-card">
					<view class="card-header">
						<view class="header-icon">
							<text class="cuIcon-profile"></text>
						</view>
						<text class="header-title">基础信息</text>
					</view>
					
					<view class="form-list">
						<view class="form-item">
							<view class="form-label">
								<text class="label-icon">👤</text>
								<text class="label-text">真实姓名</text>
								<text class="required">*</text>
							</view>
							<view class="form-input">
								<input 
									class="input-field"
									v-model="formData.realName"
									placeholder="请输入真实姓名"
									:disabled="submitting"
								/>
							</view>
						</view>
						
						<view class="form-item">
							<view class="form-label">
								<text class="label-icon">📞</text>
								<text class="label-text">联系电话</text>
							</view>
							<view class="form-input">
								<input 
									class="input-field disabled"
									v-model="userInfo.phone"
									disabled
									placeholder="系统自动获取"
								/>
							</view>
						</view>
						
						<view class="form-item">
							<view class="form-label">
								<text class="label-icon">📍</text>
								<text class="label-text">详细地址</text>
								<text class="required">*</text>
							</view>
							<view class="address-input">
								<view class="community-name">{{userInfo.community.name}}</view>
								<input 
									class="input-field"
									v-model="formData.houseInfo"
									placeholder="请输入楼栋门牌号"
									:disabled="submitting"
								/>
							</view>
						</view>
					</view>
				</view>

				<!-- 身份凭证卡片 -->
				<view class="form-card">
					<view class="card-header">
						<view class="header-icon">
							<text class="cuIcon-card"></text>
						</view>
						<view class="header-content">
							<text class="header-title">身份凭证</text>
							<text class="header-subtitle">请上传身份证正反面</text>
						</view>
					</view>
					
					<view class="upload-section">
						<uni-file-picker 
							limit="2" 
							@select="uploadImagesIdCardPic" 
							v-model="formData.idCardImage"
							title="上传用途仅限认证" 
							:image-styles="imgStyle"
							:disabled="submitting"
						></uni-file-picker>
					</view>
				</view>

				<!-- 业主凭证卡片 -->
				<view class="form-card">
					<view class="card-header">
						<view class="header-icon">
							<text class="cuIcon-form"></text>
						</view>
						<view class="header-content">
							<text class="header-title">业主凭证</text>
							<text class="header-subtitle">请上传物业费缴纳凭证 / 房产证业主信息等证明材料</text>
						</view>
					</view>
					
					<view class="upload-section">
						<uni-file-picker 
							limit="6" 
							title="上传用途仅限认证" 
							@select="uploadImages" 
							v-model="formData.images"
							:image-styles="imgStyle"
							:disabled="submitting"
						></uni-file-picker>
					</view>
				</view>

				<!-- 提示信息 -->
				<view class="tip-section">
					<view class="tip-content">
						<view class="tip-icon">
							<text class="cuIcon-warn"></text>
						</view>
						<view class="tip-text">
							<text class="tip-title">温馨提示</text>
							<text class="tip-desc">租客请上传租赁合同 / 租赁凭证</text>
						</view>
					</view>
				</view>

				<!-- 佣金提现提示 -->
				<view class="tip-section commission-tip">
					<view class="tip-content">
						<view class="tip-icon">
							<text class="cuIcon-moneybag"></text>
						</view>
						<view class="tip-text">
							<text class="tip-title">佣金提现说明</text>
							<text class="tip-desc">佣金提现需要业主认证信息与微信实名认证信息一致</text>
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 底部操作按钮 -->
		<view class="bottom-actions">
			<button 
				class="submit-btn" 
				:class="{ disabled: !isFormValid || submitting }"
				:disabled="!isFormValid || submitting"
				@click="submitInfo"
			>
				<text v-if="submitting" class="loading-text">提交中...</text>
				<text v-else>提交认证</text>
			</button>
		</view>
	</view>
</template>

<script>
	import headerSlot from '@/components/header-slot.vue';
	import config from '@/config/config';
	import storage from "@/utils/storage.js";
	import {
		editCertificationInfo,
		updataCertificationInfo
	} from "@/api/mine.js"
	import {
		getUserInfo
	} from "@/api/members";
	
	export default {
		components: {
			headerSlot,
		},
		data() {
			return {
				config,
				userInfo: {},
				submitting: false,
				formData: {
					realName: '',
					houseInfo: '', //地址
					idCardImage: [], //身份证照片
					images: [], //认证材料
					communityId: '', //小区id
				},
				imgStyle: {
					"border": { // 如果为 Boolean 值，可以控制边框显示与否
						"color": "#e0e0e0", // 边框颜色
						"radius": "12" // 边框圆角，支持百分比
					}
				},
			};
		},
		computed: {
			isFormValid() {
				return this.formData.realName.trim() && 
					   this.formData.houseInfo.trim() && 
					   this.formData.idCardImage.length > 0 && 
					   this.formData.images.length > 0;
			}
		},
		onLoad() {
			this.userInfo = storage.getUserInfo()
			this.formData = uni.getStorageSync("formData") || {
				realName: '',
				houseInfo: '',
				idCardImage: [],
				images: [],
				communityId: '',
			}
			
			// 处理编辑模式下的图片数据
			if (this.formData.id) {
				this.formData.idCardImage = this.formData.idCardImage.map(url => {
					const extension = '.' + url.split('.').pop()
					return {
						url: url,
						extname: extension,
						fileType: this.getMimeType(extension),
						status: 'success',
						original: false
					}
				})
				this.formData.images = this.formData.images.map(url => {
					const extension = '.' + url.split('.').pop()
					return {
						url: url,
						extname: extension,
						fileType: this.getMimeType(extension),
						status: 'success',
						original: false
					}
				})
			}
		},
		methods: {
			async submitInfo() {
				if (!this.isFormValid || this.submitting) return
				
				// 表单验证
				const validation = this.validateForm()
				if (!validation.isValid) {
					uni.showToast({
						title: validation.message,
						icon: "none",
					});
					return
				}
				
				try {
					this.submitting = true
					this.formData.communityId = this.userInfo.community._id
					
					if (this.formData.id) {
						// 更新认证信息
						await updataCertificationInfo(this.formData)
					} else {
						// 新增认证信息
						await editCertificationInfo(this.formData)
					}
					
					uni.showToast({
						title: "提交成功",
						icon: "success",
					});
					
					// 获取用户信息
					const user = await getUserInfo()
					storage.setUserInfo(user.data.data);
					this.formData = {}
					uni.setStorageSync('formData', {})
					
					// 延迟跳转
					setTimeout(() => {
						if (this.formData.id) {
							this.$router.redirectTo({
								url: '/pages/tabBar/mine'
							})
						} else {
							this.closePage()
						}
					}, 1500)
					
				} catch (error) {
					console.error('提交认证信息失败:', error)
					uni.showToast({
						title: '提交失败，请重试',
						icon: 'none'
					})
				} finally {
					this.submitting = false
				}
			},
			
			validateForm() {
				if (!this.formData.realName.trim()) {
					return { isValid: false, message: '请填写真实姓名' }
				}
				if (!this.formData.houseInfo.trim()) {
					return { isValid: false, message: '请输入详细地址' }
				}
				if (this.formData.idCardImage.length === 0) {
					return { isValid: false, message: '请上传身份证件' }
				}
				if (this.formData.images.length === 0) {
					return { isValid: false, message: '请上传认证材料' }
				}
				return { isValid: true, message: '' }
			},
			
			async uploadImagesIdCardPic(e) {
				await this.uploadImage(e, 'idCardImage')
			},
			
			async uploadImages(e) {
				await this.uploadImage(e, 'images')
			},
			
			async uploadImage(e, type) {
				const tempFilePath = e.tempFilePaths[0]
				if (!tempFilePath) return
				
				try {
					uni.showLoading({
						title: '上传中...'
					})
					
					const token = storage.getAccessToken()
					const uploadResult = await new Promise((resolve, reject) => {
						uni.uploadFile({
							url: `${config.commonApi}/api/upload/wechat-image`,
							filePath: tempFilePath,
							name: 'file',
							header: {
								'authorization': token
							},
							success: (uploadFileRes) => {
								try {
									const data = JSON.parse(uploadFileRes.data)
									resolve(data)
								} catch (error) {
									reject(error)
								}
							},
							fail: reject
						})
					})
					
					const imageData = {
						url: uploadResult.data.url
					}
					this.formData[type].push(imageData)
					
					uni.hideLoading()
					uni.showToast({
						title: '上传成功',
						icon: 'success'
					})
					
				} catch (error) {
					console.error('图片上传失败:', error)
					uni.hideLoading()
					uni.showToast({
						title: '上传失败，请重试',
						icon: 'none'
					})
				}
			},
			
			closePage() {
				uni.navigateBack()
			},
			
			getMimeType(extension) {
				const mimeTypes = {
					'jpg': 'image/jpeg',
					'jpeg': 'image/jpeg',
					'png': 'image/png',
					'gif': 'image/gif',
					'webp': 'image/webp',
					'bmp': 'image/bmp',
					'svg': 'image/svg+xml',
					'ico': 'image/x-icon'
				}
				const ext = extension.toLowerCase().replace('.', '')
				return mimeTypes[ext] || 'image/jpeg'
			},
		}
	}
</script>

<style lang="scss" scoped>
	.certified-owners-page {
		min-height: 100vh;
		background: #f5f7fa;
	}

	.header-container {
		display: flex;
		align-items: center;
		padding: 0 32rpx;
		width: 100%;
		height: 88rpx;
		
		.back-btn {
			margin-right: 20rpx;
			padding: 8rpx;
			
			.cuIcon-back {
				font-size: 36rpx;
				color: #2C2622;
			}
		}
		
		.page-title {
			font-weight: 600;
			font-size: 36rpx;
			color: #2C2622;
		}
	}

	.content-container {
		padding: 32rpx;
		padding-bottom: 120rpx;
	}

	.form-section {
		.form-card {
			background: #FFFFFF;
			border-radius: 20rpx;
			padding: 32rpx 24rpx;
			margin-bottom: 32rpx;
			box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
			
			.card-header {
				display: flex;
				align-items: center;
				margin-bottom: 32rpx;
				
				.header-icon {
					width: 48rpx;
					height: 48rpx;
					background: linear-gradient(135deg, #FE6100 0%, #FF6B35 100%);
					border-radius: 12rpx;
					display: flex;
					align-items: center;
					justify-content: center;
					margin-right: 16rpx;
					
					text {
						font-size: 24rpx;
						color: #FFFFFF;
					}
				}
				
				.header-content {
					flex: 1;
					
					.header-title {
						font-size: 32rpx;
						color: #2C2622;
						font-weight: 600;
						margin-bottom: 8rpx;
						display: block;
					}
					
					.header-subtitle {
						font-size: 24rpx;
						color: #8F97A2;
						line-height: 1.4;
					}
				}
			}
			
			.form-list {
				.form-item {
					margin-bottom: 32rpx;
					
					&:last-child {
						margin-bottom: 0;
					}
					
					.form-label {
						display: flex;
						align-items: center;
						margin-bottom: 16rpx;
						
						.label-icon {
							font-size: 28rpx;
							margin-right: 12rpx;
						}
						
						.label-text {
							font-size: 28rpx;
							color: #606266;
							font-weight: 500;
						}
						
						.required {
							color: #F56C6C;
							font-size: 28rpx;
							margin-left: 8rpx;
						}
					}
					
					.form-input {
						.input-field {
							width: 100%;
							height: 88rpx;
							background: #f8f9fa;
							border: 2rpx solid #e9ecef;
							border-radius: 12rpx;
							padding: 0 24rpx;
							font-size: 28rpx;
							color: #2C2622;
							transition: all 0.2s;
							
							&:focus {
								border-color: #FE6100;
								background: #FFFFFF;
							}
							
							&.disabled {
								background: #f5f5f5;
								color: #8F97A2;
								cursor: not-allowed;
							}
						}
					}
					
					.address-input {
						.community-name {
							background: #f8f9fa;
							border: 2rpx solid #e9ecef;
							border-radius: 12rpx;
							padding: 24rpx;
							font-size: 28rpx;
							color: #2C2622;
							margin-bottom: 16rpx;
							font-weight: 500;
						}
						
						.input-field {
							width: 100%;
							height: 88rpx;
							background: #f8f9fa;
							border: 2rpx solid #e9ecef;
							border-radius: 12rpx;
							padding: 0 24rpx;
							font-size: 28rpx;
							color: #2C2622;
							transition: all 0.2s;
							
							&:focus {
								border-color: #FE6100;
								background: #FFFFFF;
							}
						}
					}
				}
			}
			
			.upload-section {
				padding: 0;
			}
		}
	}

	.tip-section {
		background: #fff3cd;
		border: 1rpx solid #ffeaa7;
		border-radius: 16rpx;
		padding: 24rpx;
		margin-bottom: 32rpx;
		
		.tip-content {
			display: flex;
			align-items: flex-start;
			
			.tip-icon {
				margin-right: 16rpx;
				margin-top: 4rpx;
				
				.cuIcon-warn {
					font-size: 32rpx;
					color: #f39c12;
				}
			}
			
			.tip-text {
				flex: 1;
				
				.tip-title {
					font-size: 28rpx;
					color: #856404;
					font-weight: 600;
					margin-bottom: 8rpx;
					display: block;
				}
				
				.tip-desc {
					font-size: 26rpx;
					color: #856404;
					line-height: 1.4;
				}
			}
		}
		
		&.commission-tip {
			background: #e8f4fd;
			border: 1rpx solid #b3d9ff;
			
			.tip-icon {
				.cuIcon-moneybag {
					font-size: 32rpx;
					color: #1890ff;
				}
			}
			
			.tip-text {
				.tip-title {
					color: #0050b3;
				}
				
				.tip-desc {
					color: #0050b3;
				}
			}
		}
	}

	.bottom-actions {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		padding: 32rpx;
		background: #FFFFFF;
		border-top: 1rpx solid #f0f0f0;
		box-shadow: 0 -4rpx 20rpx rgba(0, 0, 0, 0.08);
		
		.submit-btn {
			display: flex;
			align-items: center;
			justify-content: center;
			width: 100%;
			height: 88rpx;
			background: linear-gradient(135deg, #FE6100 0%, #FF6B35 100%);
			color: #FFFFFF;
			border-radius: 16rpx;
			font-size: 32rpx;
			font-weight: 600;
			border: none;
			transition: all 0.2s;
			
			&:active {
				transform: scale(0.98);
			}
			
			&.disabled {
				background: #c0c4cc;
				opacity: 0.6;
			}
			
			.loading-text {
				display: flex;
				align-items: center;
				
				&::before {
					content: '';
					width: 24rpx;
					height: 24rpx;
					border: 2rpx solid #FFFFFF;
					border-top: 2rpx solid transparent;
					border-radius: 50%;
					animation: spin 1s linear infinite;
					margin-right: 12rpx;
				}
			}
		}
	}

	@keyframes spin {
		0% { transform: rotate(0deg); }
		100% { transform: rotate(360deg); }
	}
</style>